package edu.ynu.se.xiecheng.achitectureclass.project.controller;

import edu.ynu.se.xiecheng.achitectureclass.project.common.Result;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.Data;
import edu.ynu.se.xiecheng.achitectureclass.project.service.DataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/soil-data")
public class DataController {

    private static final Logger log = LoggerFactory.getLogger(DataController.class);

    @Autowired
    private DataService dataService;

    // 查询所有土壤检测数据
    @GetMapping
    public Result<List<Data>> getAllData() {
        log.info("查询所有土壤检测数据");
        List<Data> dataList = dataService.getAllData();
        if (dataList == null || dataList.isEmpty()) {
            log.warn("未找到任何土壤检测数据");
            return Result.error(404, "未找到土壤检测数据");
        }
        return Result.success(dataList);
    }

    // 根据 serialId 查询土壤检测数据
    @GetMapping("/{serialId}")
    public Result<Data> getDataBySerialId(@PathVariable String serialId) {
        log.info("查询土壤检测数据，serialId: {}", serialId);
        Data data = dataService.getDataBySerialId(serialId);
        if (data == null) {
            log.warn("未找到 serialId 为 {} 的土壤检测数据", serialId);
            return Result.error(404, "未找到 serialId 为 " + serialId + " 的土壤检测数据");
        }
        return Result.success(data);
    }

    // 删除土壤检测数据（逻辑删除）
    @DeleteMapping("/{serialId}")
    public Result<String> deleteDataBySerialId(@PathVariable String serialId) {
        log.info("删除土壤检测数据，serialId: {}", serialId);
        dataService.deleteDataBySerialId(serialId);
        return Result.success("数据删除成功");
    }

    // 插入土壤检测数据
    @PostMapping
    public Result<String> insertData(@RequestBody Data data) {
        log.info("插入土壤检测数据: {}", data);
        dataService.insertData(data);
        return Result.success("数据插入成功");
    }

    // 更新土壤检测数据
    @PutMapping("/{serialId}")
    public Result<String> updateData(@PathVariable String serialId, @RequestBody Data data) {
        log.info("更新土壤检测数据，serialId: {}, data: {}", serialId, data);
        dataService.updateData(serialId, data.getBoxNo(), data.getName(), data.getValue());
        return Result.success("数据更新成功");
    }

    // 根据 name 属性查询土壤数据
    @GetMapping("/name/{name}")
    public Result<List<Data>> getSoilDataByName(@PathVariable String name) {
        log.info("查询特定类型的土壤检测数据，name: {}", name);
        List<Data> dataList = dataService.getSoilDataByName(name);
        if (dataList == null || dataList.isEmpty()) {
            log.warn("未找到 name 为 {} 的土壤检测数据", name);
            return Result.error(404, "未找到 name 为 " + name + " 的土壤检测数据");
        }
        return Result.success(dataList);
    }
}